package com.example.administrator.newxlmedical;

import android.content.Intent;
import android.os.Bundle;
import android.os.Environment;
import android.os.Message;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.WindowManager;
import android.view.inputmethod.EditorInfo;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.Filter;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.Spinner;
import android.widget.TextView;

import com.example.administrator.baseproject.BaseActivity;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;

import adapters.CountSpinnerAdapter;
import adapters.InventoryAdapter;
import adapters.InventoryErrorAdapter;
import beans.GoodsDetailInfoBean;
import beans.ItemEntity;
import beans.NewUserInfoBean;
import beans.OperateGoodsDetailsBean;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import constants.Constants;
import constants.HandlerConstant;
import customhandler.MyHandler;
import interfaces.MyItemClickListener;
import netframe.GetRetrofit;
import netframe.IFuzzySearchRule;
import netframe.MyAction1;
import netframe.NetAddress;
import netframe.NetReconnectFunc1;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Action1;
import rx.schedulers.Schedulers;
import singleton.SingletonClass;
import utils.ActivityUtil;
import utils.CustomSharedPreferencePath;
import utils.DefaultFuzzySearchRule;
import utils.FormateUtils;
import utils.FuzzySearchUtils;
import utils.InventorySortUtils;
import utils.ObjectSaveUtil;
import utils.ScreenUtils;
import utils.TimeUtil;
import utils.ToastUtil;
import utils.ViewUtil;

import static android.widget.AbsListView.OnScrollListener.SCROLL_STATE_IDLE;

public class InventoryActivity extends BaseActivity {
    @BindView(R.id.rv_inventory_activity)
    RecyclerView recyclerView;
    @BindView(R.id.fl_inventory_empty)
    FrameLayout flEmpty;
    @BindView(R.id.iv_inventory_home)
    ImageView ivHome;
    @BindView(R.id.rl_inventory_table_head)
    RelativeLayout rlTitle;
    @BindView(R.id.iv_inventory_goods_sort)
    ImageView ivGoodsSort;
    @BindView(R.id.rl_inventory_goods_sort)
    RelativeLayout rlInventoryGoodsSort;
    @BindView(R.id.iv_inventory_supplier_sort)
    ImageView ivSupplierSort;
    @BindView(R.id.rl_inventory_supplier_sort)
    RelativeLayout rlInventorySupplierSort;
    @BindView(R.id.remind_goods)
    TextView tvGoods;
    @BindView(R.id.remind_supplier)
    TextView tvSupplier;
    @BindView(R.id.remind_size)
    TextView tvSpecification;
    @BindView(R.id.iv_inventory_specification_sort)
    ImageView ivSpecificationSort;
    @BindView(R.id.rl_inventory_specification_sort)
    RelativeLayout rlSpecificationSort;
    @BindView(R.id.remind_count)
    TextView tvNumber;
    @BindView(R.id.iv_inventory_number_sort)
    ImageView ivNumberSort;
    @BindView(R.id.rl_inventory_number_sort)
    RelativeLayout rlNumberSort;
    @BindView(R.id.sp_inventory_cabinet)
    Spinner spCabinet;
    @BindView(R.id.sp_inventory_query)
    Spinner spQuery;
    @BindView(R.id.et_inventory_supplier)
    EditText etQuery;
    @BindView(R.id.tv_inventory_search)
    TextView tvSearch;
    @BindView(R.id.remind_cabinet)
    TextView tvCabinet;
    @BindView(R.id.iv_inventory_cabinetsort)
    ImageView ivCabinetSort;
    @BindView(R.id.rl_inventory_cabinet_sort)
    RelativeLayout rlCabinetSort;
    @BindView(R.id.tv_inventory_count)
    TextView tvCount;
    @BindView(R.id.ll_inventory_count)
    LinearLayout llCount;


    private int selectCabinet;
    private InventoryAdapter adapter;
    private InventoryErrorAdapter errorAdapter;
    private boolean isSortGoods, isSortSpecification, isSortSupplier, isSortNumber, isSortCabinet;
    private int sortGoods, sortSpecification, sortSupplier, sortNumber, sortCabinet;
    private MyHandler allHandler = SingletonClass.getSingleton(MyHandler.class);
    private List<OperateGoodsDetailsBean.DataBean> allList = new ArrayList<>();
    private List<OperateGoodsDetailsBean.DataBean> list = new ArrayList<>();
    private List<OperateGoodsDetailsBean.DataBean> sortlist = new ArrayList<>();
    private List<OperateGoodsDetailsBean.DataBean> searchlist = new ArrayList<>();
    private List<OperateGoodsDetailsBean.DataBean> fuzzylist = new ArrayList<>();
    private List<OperateGoodsDetailsBean.DataBean> saveErrorlist = new ArrayList<>();
    private Map<String,Integer> rfidMap = new HashMap<>();
    private List<String> rfidList = new ArrayList<>();
    private int correctSize, cabinetSize;
    private int allSize;
    private int cabinetPosition;
    private List<Integer> cabientList;
    private CountSpinnerAdapter cabinetAdapter, queryAdapter;
    private String[] cabinetData ;
    private String[] queryData = {"全部", "物资名称", "规格型号", "供应商", "条码"};
    private int mPosition, mSearchPosition;
    private boolean isFrist = true;
    private boolean isFristError = true;
    private int lastLoadDataItemPosition;
    private IFuzzySearchRule mIFuzzySearchRule;
    private int fuzzySearchIndex = 1;
    private FuzzySearchFilter fuzzySearchFilter;
    private int searchCount;
    private int count;
    private int searchIndex;
    private int cabinetNumber;
    private String[] split1;
    private NewUserInfoBean.DataBean userInfoBean;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_inventory);
        ButterKnife.bind(this);
        getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_PAN);
    }

    @Override
    public void initView() {
        super.initView();
        Map<String, Integer> readMap = (Map<String, Integer>) ObjectSaveUtil.readObject(this, Constants.CABINET_NUMBER, Constants.CABINET_NUMBER);
        userInfoBean = (NewUserInfoBean.DataBean) ObjectSaveUtil.readObject(this, Constants.USER_INFO_BEAN, Constants.USER_INFO_BEAN);
        if (readMap != null && readMap.size() != 0) {
            cabinetData = new String[readMap.size() + 1];
            Set setMap = readMap.entrySet();
            Iterator mapInterator = setMap.iterator();
            List<Integer> cabinetList = new ArrayList<>();
            while (mapInterator.hasNext()) {
                Map.Entry mapentry = (Map.Entry) mapInterator.next();
                int number = (int) mapentry.getValue();
                cabinetList.add(number);
            }
            Collections.sort(cabinetList);
            cabinetData[0] = "全部";
            for (int i = 0; i < cabinetList.size(); i++) {
                cabinetData[i + 1] = cabinetList.get(i)+"";
            }
        } else {
            cabinetData = new String[]{"全部"};
        }

        allHandler.sendEmptyMessageDelayed(HandlerConstant.INVENTORY_TIME_OUT, 20000);

        LinearLayoutManager manager = new LinearLayoutManager(this);
        adapter = new InventoryAdapter(InventoryActivity.this, list);
        recyclerView.setLayoutManager(manager);
        recyclerView.setAdapter(adapter);

        cabinetAdapter = new CountSpinnerAdapter(this, R.layout.time_out_spinner_layout, cabinetData);
        cabinetAdapter.setDropDownViewResource(R.layout.spinner_bg);
        spCabinet.setAdapter(cabinetAdapter);

        queryAdapter = new CountSpinnerAdapter(this, R.layout.count_spinner_layout, queryData);
        queryAdapter.setDropDownViewResource(R.layout.spinner_bg);
        spQuery.setAdapter(queryAdapter);

        showLoadingView(flEmpty);
        mIFuzzySearchRule = new DefaultFuzzySearchRule();
        fuzzySearchFilter = new FuzzySearchFilter();
        // 获取 柜子编号时存储的 所有柜号

        cabientList = new ArrayList<>();
        if (readMap != null && readMap.size() != 0) {
            Set setMap = readMap.entrySet();
            Iterator mapInterator = setMap.iterator();
            while (mapInterator.hasNext()) {
                Map.Entry mapentry = (Map.Entry) mapInterator.next();
                int cabinet = (int) mapentry.getValue();
                cabientList.add(cabinet);
            }
        }

        // 轮询盘点全部柜子
        if (cabientList.size() > 0) {

            Collections.sort(cabientList);
            startInventory(cabinetPosition++);

        } else {
            hideLoadingView();
            showEmptyView(flEmpty);
        }
    }

    @Override
    protected void setListener() {

        // 柜子
        spCabinet.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                mPosition = position;
                cabinetAdapter.setSelectPosition(mPosition);
                if (position != 0) {
                    cabinetNumber = Integer.parseInt(cabinetData[position]);
                } else {
                    cabinetNumber = 0;
                }
                if (!isFrist) {
                    searchCabinet(cabinetNumber);
                } else {
                    isFrist = false;
                }
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });

        recyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
                super.onScrollStateChanged(recyclerView, newState);
                if (newState == SCROLL_STATE_IDLE && lastLoadDataItemPosition == adapter.getItemCount()) {
                    ToastUtil.showToast(InventoryActivity.this, "没有更多数据了!");
                }
            }

            @Override
            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);
                RecyclerView.LayoutManager layoutManager = recyclerView.getLayoutManager();
                if (layoutManager instanceof LinearLayoutManager) {
                    LinearLayoutManager manager = (LinearLayoutManager) layoutManager;
                    int lastVisibleItem = manager.findLastCompletelyVisibleItemPosition();
                    lastLoadDataItemPosition = lastVisibleItem + 1;
                }
            }
        });

        // 搜索
        spQuery.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                mSearchPosition = position;
                searchIndex = position;
                queryAdapter.setSelectPosition(mSearchPosition);

            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });

        adapter.setItemClickListener(new MyItemClickListener() {
            @Override
            public void onItemClick(View view, int position) {
                OperateGoodsDetailsBean.DataBean bean = list.get(position);

                GoodsDetailInfoBean infoBean = new GoodsDetailInfoBean();
                infoBean.setName(bean.getGoodName());
                infoBean.setBarCode(bean.getBarCodeList());
                infoBean.setSpecification(bean.getSpecification());
                infoBean.setSupplier(bean.getManufacturer());
                infoBean.setUnit(bean.getGoodsUnit());
                infoBean.setNumber(bean.getNumber());
                infoBean.setStatus(bean.getStatus());

                infoBean.setTitle("盘点");
                infoBean.setTitleContent("物品详情");

                Bundle bundle = new Bundle();
                bundle.putSerializable(Constants.GOODS_DETIAL_INFO, infoBean);
                Intent intent = new Intent(InventoryActivity.this, GoodsDetialActivity.class);
                intent.putExtra("bundle", bundle);
                startActivity(intent);
            }
        });

        etQuery.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {

                if (actionId == EditorInfo.IME_ACTION_SEARCH || (event != null && event.getKeyCode() == KeyEvent.KEYCODE_ENTER)) {
                    sort(0);
                    ScreenUtils.closeKeybord(etQuery, InventoryActivity.this);
                    searchToButton();
                    return true;
                }

                return false;
            }
        });

    }

    @OnClick({R.id.iv_inventory_home, R.id.rl_inventory_goods_sort,
            R.id.rl_inventory_supplier_sort, R.id.rl_inventory_specification_sort, R.id.rl_inventory_number_sort,
            R.id.rl_inventory_cabinet_sort, R.id.tv_inventory_search
    })
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.iv_inventory_home:
                ActivityUtil.jumpToActivity(InventoryActivity.this, MainActivity.class);
                finish();
                break;
            case R.id.rl_inventory_goods_sort:
                sort(1);
                break;
            case R.id.rl_inventory_supplier_sort:
                sort(2);
                break;
            case R.id.rl_inventory_specification_sort:
                sort(3);
                break;
            case R.id.rl_inventory_number_sort:
                sort(4);
                break;
            case R.id.rl_inventory_cabinet_sort:
                sort(5);
                break;
            case R.id.tv_inventory_search:
                sort(0);
                ScreenUtils.closeKeybord(etQuery, InventoryActivity.this);
                searchToButton();
                break;
        }
    }

    /**
     *  获取相关RFID信息
     * @param
     * @param cabinetCode  传空
     * @param type  3
     */
    private void getGoodsDetails(final String cabinetCode, final String type) {
        GetRetrofit.getInstance().getGoodDetailsInventory(NetAddress.token, NetAddress.machineCode, rfidList, "", cabinetCode, type,userInfoBean.getID()+"",NetAddress.deptCode)
                .subscribeOn(Schedulers.io())
                .retryWhen(new NetReconnectFunc1())
                .observeOn(AndroidSchedulers.mainThread()).subscribe(new Action1<OperateGoodsDetailsBean>() {
            @Override
            public void call(OperateGoodsDetailsBean goodsDetailsBean) {

                List<OperateGoodsDetailsBean.DataBean> dataBean = goodsDetailsBean.getData();
                List<OperateGoodsDetailsBean.DataBean> aberrantData = goodsDetailsBean.getAberrantData();
                if (dataBean != null && dataBean.size() > 0) {
                    saveToFile(dataBean.size()+"");
                    correctSize += dataBean.size();
                    List<OperateGoodsDetailsBean.DataBean> distinctList = FormateUtils.getInventoryDistinctList(dataBean);
                    InventorySortUtils.sortCabinet(distinctList, true);
                    ckeckCabinet(distinctList);
                }
                // 按物资名排序正常物资， 异常置顶

                if (aberrantData != null && aberrantData.size() > 0) {
                    correctSize += aberrantData.size();
                    setSelectCabinet(aberrantData);
                    List<OperateGoodsDetailsBean.DataBean> errorList = FormateUtils.getInventoryDistinctList(aberrantData);
                    InventorySortUtils.sortCabinet(errorList, true);
                    sortlist.addAll(0, errorList);
                    saveToFile(aberrantData.size()+"");
                }

                if (sortlist.size() != 0) {
                    fuzzylist.clear();
                    list.addAll(sortlist);
                    allList.addAll(sortlist);
                    searchlist.addAll(sortlist);
                    fuzzylist.addAll(sortlist);
                    allSize = correctSize;
                    cabinetSize = allSize;
                    tvCount.setText(correctSize + "");
                    llCount.setVisibility(View.VISIBLE);
                    addErrorGoods(saveErrorlist);
                    adapter.notifyDataSetChanged();
                    hideLoadingView();
                } else {
                    ToastUtil.showToast(InventoryActivity.this, "暂无数据!");
                    saveToFile("getGoodsDetails null");
                    hideLoadingView();
                    showEmptyView(flEmpty);
                }


            }
        }, new MyAction1() {
            @Override
            public void call(Throwable throwable) {
                super.call(throwable);
                hideLoadingView();
                showEmptyView(flEmpty);
                ToastUtil.showToast(InventoryActivity.this, throwable.getMessage());
            }
        });

    }

    public void ckeckCabinet(List<OperateGoodsDetailsBean.DataBean> distinctList){
        List<OperateGoodsDetailsBean.DataBean> showList = new ArrayList<>();
        for (int i = 0; i < cabientList.size(); i++) {
            List<OperateGoodsDetailsBean.DataBean> list = new ArrayList<>();
            for (int i1 = 0; i1 < distinctList.size(); i1++) {
                OperateGoodsDetailsBean.DataBean dataBean = distinctList.get(i1);
                if (dataBean.getLogicNumber().equals(cabientList.get(i)+"")){
                    list.add(dataBean);
                }
            }
            if (list.size() != 0){
                InventorySortUtils.sortGoodsName(list,true);
                showList.addAll(list);
            }
        }
        sortlist.clear();
        sortlist.addAll(showList);
    }

    private void setSelectCabinet(List<OperateGoodsDetailsBean.DataBean> error) {
        if (error != null) {
            for (int i = 0; i < error.size(); i++) {
                OperateGoodsDetailsBean.DataBean dataBean = error.get(i);
                dataBean.setLogicNumber(String.valueOf(rfidMap.get(dataBean.getRfidCode())));
                saveErrorlist.add(dataBean);
            }
        }
    }

    private void addErrorGoods(List<OperateGoodsDetailsBean.DataBean> error) {
        Map<String, OperateGoodsDetailsBean.DataBean> errorMap = new HashMap<>();

        List<OperateGoodsDetailsBean.DataBean> list = new ArrayList<>();
        list.addAll(error);

        for (int i = 0; i < list.size(); i++) {
            OperateGoodsDetailsBean.DataBean dataBean = list.get(i);
            dataBean.setErrorRecordTime(TimeUtil.getMillisecondDate());
            if (dataBean.getStatus() != 3) {
                String key = dataBean.getGID() + dataBean.getSpecification() + dataBean.getManufacturer() + dataBean.getStatus();
                if (errorMap.get(key) != null) {
                    String millisecondDate = TimeUtil.getMillisecondDate();
                    OperateGoodsDetailsBean.DataBean bean = errorMap.get(key);
                    bean.setNumber(bean.getNumber() + 1);
                    bean.getBarCodeList().add(dataBean.getBarCode() + Constants.INCREASE_DECREASE_SPLIT + millisecondDate);
                    bean.setErrorRecordTime(millisecondDate);
                    bean.setSelectCabinet(selectCabinet + "");
                    errorMap.put(key, bean);
                } else {
                    Log.e("EEEE", "else " + TimeUtil.getMillisecondDate());
                    errorMap.put(key, dataBean);
                }
            }
        }

        CustomSharedPreferencePath.saveData(this, Constants.RECORD_ERROR_GOODS, errorMap);
    }

    @Override
    protected void onHandleMessage(Message msg) {
        super.onHandleMessage(msg);
        switch (msg.what) {

            case HandlerConstant.SCAN_COMPLETE:
                allHandler.removeMessages(HandlerConstant.INVENTORY_TIME_OUT);
                //得到扫描的结果,请求网络
                String s = (String) msg.obj;
                ToastUtil.showToastlog(this, s);
                saveToFile(s);
                selectCabinet = msg.arg1;
                String[] split = s.split(Constants.INCREASE_DECREASE_SPLIT);

                if (split.length >= 1) {
                    if (!TextUtils.isEmpty(split[0])) {
                        // 添加rfid
                        ArrayList<String> rfidCodes = FormateUtils.getRfidCodes(split[0]);
                        rfidList.addAll(rfidCodes);
                        for (String rfidCode : rfidCodes) {
                            rfidMap.put(rfidCode,selectCabinet);
                        }
                    } else {
                        saveToFile("SPLIT NULL : EMPTY!");
                    }
                } else {
                    saveToFile("split.length : EMPTY!");
                }

                // 如果不是最后一个柜子 就继续盘点
                if (cabinetPosition < cabientList.size()) {
                    Log.e("CCC", "SCAN_COMPLETE_ERROR  message " + cabinetPosition);
                    startInventory(cabinetPosition++);
                }else {
                    if (rfidMap.size() != 0){
                        getGoodsDetails("", "3");
                    }else {
                        addErrorGoods(saveErrorlist);
                        hideLoadingView();
                        showEmptyView(flEmpty);
                    }
                }

                break;

            case HandlerConstant.SCAN_COMPLETE_ERROR:
                saveToFile("SCAN_COMPLETE_ERROR");
                showData();
                break;

            case HandlerConstant.INVENTORY_TIME_OUT:
                ToastUtil.showToastlog(InventoryActivity.this, "盘点超时!");
                saveToFile("TIME_OUT");
                hideLoadingView();
                showEmptyView(flEmpty);
                break;

            case HandlerConstant.FUZZY_SEARCH:
                count++;
                if (count == searchCount) {
                    count = 0;
                    Log.e(TAG, "searchToButton: " + sortlist.size());
                    list.clear();
                    if (sortlist.size() != 0) {
                        list.addAll(sortlist);
                        tvCount.setText(correctSize + "");
                    } else {
                        Log.e(TAG, "else3:");
                        tvCount.setText("0");
                        showEmptyView(flEmpty);
                    }
                    mSearchPosition = searchIndex;
                    adapter.notifyDataSetChanged();
                    hideLoadingView();
                } else {
                    searchlist.clear();
                    searchlist.addAll(sortlist);
                    mSearchPosition = 2;
                    fuzzySearchFilter.filter(split1[1]);
                }
                break;
        }
    }

    private void startInventory(int cabinetPosition) {
        Message message = allHandler.obtainMessage();
        message.what = HandlerConstant.BEGIN_INVENTORY;
        message.obj = cabientList.get(cabinetPosition);
        allHandler.sendMessage(message);
    }

    private void showData() {
        // 如果不是最后一个柜子 就继续盘点
        if (cabinetPosition < cabientList.size()) {
            Log.e("CCC", "SCAN_COMPLETE_ERROR  message " + cabinetPosition);
            startInventory(cabinetPosition++);
        }else {
            if (rfidMap.size() != 0){
                getGoodsDetails("", "3");
            }else {
                addErrorGoods(saveErrorlist);
                hideLoadingView();
                showEmptyView(flEmpty);
            }
        }
    }

    private void sort(int type) {
        if (type == 1) { // 按物品名排序
            if (sortGoods != 2) {
                isSortGoods = !isSortGoods;
                sortGoods++;
                InventorySortUtils.sortGoodsName(list, isSortGoods);
            } else {
                clearSortDate();
            }
        } else {
            sortGoods = 0;
            isSortGoods = false;
        }

        if (type == 2) { // 按供应商排序
            if (sortSupplier != 2) {
                isSortSupplier = !isSortSupplier;
                sortSupplier++;
                InventorySortUtils.sortGoodsSupplier(list, isSortSupplier);
            } else {
                clearSortDate();
            }
        } else {
            sortSupplier = 0;
            isSortSupplier = false;
        }

        if (type == 3) { // 按供应商排序
            if (sortSpecification != 2) {
                sortSpecification++;
                isSortSpecification = !isSortSpecification;
                InventorySortUtils.sortGoodsSpecification(list, isSortSpecification);
            } else {
                clearSortDate();
            }
        } else {
            sortSpecification = 0;
            isSortSpecification = false;
        }

        if (type == 4) {
            if (sortNumber != 2) {
                sortNumber++;
                isSortNumber = !isSortNumber;
                InventorySortUtils.sortGoodsNumber(list, isSortNumber);
            } else {
                clearSortDate();
            }
        } else {
            sortNumber = 0;
            isSortNumber = false;
        }

        if (type == 5) {
            if (sortCabinet != 2) {
                sortCabinet++;
                isSortCabinet = !isSortCabinet;
                InventorySortUtils.sortCabinet(list, isSortCabinet);
            } else {
                clearSortDate();
            }
        } else {
            sortCabinet = 0;
            isSortCabinet = false;
        }

        ViewUtil.setSortColor(this, tvGoods, ivGoodsSort, sortGoods);
        ViewUtil.setSortColor(this, tvSupplier, ivSupplierSort, sortSupplier);
        ViewUtil.setSortColor(this, tvSpecification, ivSpecificationSort, sortSpecification);
        ViewUtil.setSortColor(this, tvNumber, ivNumberSort, sortNumber);
        ViewUtil.setSortColor(this, tvCabinet, ivCabinetSort, sortCabinet);

        adapter.notifyDataSetChanged();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        allHandler.sendEmptyMessage(HandlerConstant.END_INVENTORY);
        if (selectCabinet != 0) {
            Message message = allHandler.obtainMessage();
            message.obj = selectCabinet;
            message.what = HandlerConstant.FLASH_OFF;
            allHandler.sendMessage(message);
        }
    }

    private void clearSortDate() {
        list.clear();
        list.addAll(sortlist);

        sortGoods = 0;
        sortSpecification = 0;
        sortSupplier = 0;
        sortNumber = 0;
        sortCabinet = 0;
    }

    /**
     *  保存盘点异常信息
     * @param receiveData
     */
    public void saveToFile(String receiveData) {
        StringBuffer sb = new StringBuffer();
        try {

            if (Environment.getExternalStorageState().equals(
                    Environment.MEDIA_MOUNTED)) {
                DateFormat formatter = new SimpleDateFormat("yyyy-MM-dd-HH-mm-ss");
                String time = formatter.format(new Date());
                sb.append(time);
                sb.append("  ----------:  ");
                sb.append(receiveData);
                sb.append("  ----------;  ");
                sb.append("\r\n");
                String fileName = TimeUtil.getYear() + "-" + (TimeUtil.getMonth() + 1) + "-" + TimeUtil.getDay() + ".log";
                String path = Environment.getExternalStorageDirectory().getAbsolutePath() + "/InventoryError/";
                File dir = new File(path);
                if (!dir.exists()) {
                    dir.mkdirs();
                }
                FileOutputStream fos = new FileOutputStream(path + fileName, true);
                fos.write(sb.toString().getBytes());
                fos.flush();
                fos.close();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     *  按柜号查询
     * @param position
     */
    private void searchCabinet(final int position) {
        etQuery.setText("");
        hideEmptyView();
        showLoadingView(flEmpty);
        if (allList != null && allList.size() != 0) {
            searchlist.clear();
            fuzzylist.clear();
            sortlist.clear();
            correctSize = 0;
            cabinetSize = 0;
            if (position != 0) {
                for (int i = 0; i < allList.size(); i++) {
                    OperateGoodsDetailsBean.DataBean dataBean = allList.get(i);
                    String cabinet = dataBean.getLogicNumber();
                    if (cabinet.equals(position + "")) {
                        searchlist.add(dataBean);
                        fuzzylist.add(dataBean);
                        sortlist.add(dataBean);
                        correctSize += dataBean.getNumber();
                        cabinetSize += dataBean.getNumber();
                    }
                }
            } else {
                correctSize = allSize;
                cabinetSize = allSize;
                searchlist.addAll(allList);
                fuzzylist.addAll(allList);
                sortlist.addAll(allList);
            }

            list.clear();
            if (searchlist.size() != 0) {
                list.addAll(searchlist);
                tvCount.setText(correctSize + "");
            } else {
                tvCount.setText("0");
                showEmptyView(flEmpty);
            }
            adapter.notifyDataSetChanged();
            hideLoadingView();

        } else {
            hideLoadingView();
            showEmptyView(flEmpty);
        }

    }

    /**
     *  点击 查询 按钮
     */
    private void searchToButton() {
        hideEmptyView();
        showLoadingView(flEmpty);

        String text = etQuery.getText().toString().trim();
        if (!TextUtils.isEmpty(text)) {
            searchlist.clear();
            searchlist.addAll(fuzzylist);
            split1 = text.split(" ");
            searchCount = split1.length;

            if (searchlist.size() > 0) {
                sortlist.clear();
                correctSize = 0;
                fuzzySearchIndex = mSearchPosition;
                if (mSearchPosition == 4) {
                    for (int i = 0; i < searchlist.size(); i++) {
                        OperateGoodsDetailsBean.DataBean dataBean = searchlist.get(i);
                        List<String> barCodeList = dataBean.getBarCodeList();
                        if (barCodeList != null) {
                            int count = 0;
                            for (int i1 = 0; i1 < barCodeList.size(); i1++) {
                                String[] split = barCodeList.get(i1).split(Constants.INCREASE_DECREASE_SPLIT);
                                if (split[0].startsWith(text) || split[0].endsWith(text)) {
                                    sortlist.add(dataBean);
                                    count++;
                                }
                            }
                            if (count != 0) {
                                correctSize += dataBean.getNumber();
                            }
                        }
                    }
                    sendEmptyMessage(HandlerConstant.FUZZY_SEARCH);
                } else if (mSearchPosition == 0) {

                    for (int i = 0; i < searchlist.size(); i++) {
                        OperateGoodsDetailsBean.DataBean dataBean = searchlist.get(i);

                        if (searchCount == 1) {
                            List<String> barCodeList = dataBean.getBarCodeList();
                            if (barCodeList != null) {
                                for (int i1 = 0; i1 < barCodeList.size(); i1++) {
                                    Log.e(TAG, "searchToButton: " + barCodeList.get(i1) + "   " + text);
                                    String[] split = barCodeList.get(i1).split(Constants.INCREASE_DECREASE_SPLIT);
                                    if (split[0].startsWith(text) || split[0].endsWith(text)) {
                                        if (!sortlist.contains(dataBean)) {
                                            sortlist.add(dataBean);
                                            correctSize += dataBean.getNumber();
                                            break;
                                        }
                                    }
                                }
                            }
                        } else {
                            mSearchPosition = 1;
                        }
                    }
                    fuzzySearchFilter.filter(split1[0]);
                } else {
                    // 中文首字母模糊搜索 支持中文 不支持拼音 不支持符号
                    fuzzySearchFilter.filter(text);
                }

            } else {
                Log.e(TAG, "else2:");
                tvCount.setText("0");
                showEmptyView(flEmpty);
                hideLoadingView();
            }
        } else {
            hideLoadingView();
            if (fuzzylist.size() != 0) {
                list.clear();
                list.addAll(fuzzylist);
                tvCount.setText(cabinetSize + "");
                adapter.notifyDataSetChanged();
            } else {
                Log.e(TAG, "else1:");
                showEmptyView(flEmpty);
                tvCount.setText("0");
            }
        }

    }

    /**
     *  中文首字母搜索
     */
    private class FuzzySearchFilter extends Filter {

        /**
         * 执行过滤操作,如果搜索的关键字为空，默认所有结果
         */

        @Override
        protected FilterResults performFiltering(CharSequence constraint) {
            List<ItemEntity> dateList = FuzzySearchUtils.fillData(searchlist, fuzzySearchIndex);
            FilterResults result = new FilterResults();
            List<ItemEntity> filterList = new ArrayList<>();
            for (ItemEntity item : dateList) {
                if (mIFuzzySearchRule.accept(constraint, item.getSourceKey(), item.getFuzzyKey())) {
                    filterList.add(item);
                }
            }
            result.values = filterList;
            result.count = filterList.size();
            return result;
        }

        /**
         * 得到过滤结果
         */
        @SuppressWarnings("unchecked")
        @Override
        protected void publishResults(CharSequence constraint, FilterResults results) {
            List<ItemEntity> mDataList = (List<ItemEntity>) results.values;
            sortlist.clear();
            correctSize = 0;
            if (mDataList != null && mDataList.size() != 0) {
                for (int i = 0; i < mDataList.size(); i++) {
                    Log.e("FFFF", "publishResults: " + mDataList.get(i).getBean().getGoodName());
                    if (!sortlist.contains(mDataList.get(i).getBean())) {
                        correctSize += mDataList.get(i).getBean().getNumber();
                        sortlist.add(mDataList.get(i).getBean());
                    }
                }
            }
            sendEmptyMessage(HandlerConstant.FUZZY_SEARCH);
        }
    }
}
